/***************************************************************************
 *   This file is part of KLabeler                                         *
 *   Copyright (C) 2010 by Luca Bellonda                                   *
 *   some parts Copyright (C) 2007 Ivan Kukic <ivan.cukic(at)kde.org>      *
 *   lbellonda _at_ gmail.com                                              *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "log.h"
#include "config-klabeler.h"
#include <QDateTime>
#include <QDataStream>
#include <QDir>
#include <KNotification>
#include <KIcon>
#include <KIconLoader>
#include <KConfigGroup>
#include <KSharedConfigPtr>
#include <KStandardDirs>
#include <KLocale>
#include "lib/Config.h"

#define SEPARATOR   "|"


bool TLogger::isLoggable(const ELogLevel level)
{
    if (level >= _level) {
        return true ;
    }
    return false ;
}

void TLogger::log(
    const ELogLevel level,
    const LogParam *source,
    const QString & message)
{
    if (!isEnabled()) {
        return;
    }
    if (level < _level) {
        return ;
    }
    if (!_init) {
        start();
    }
    if (!_file.isOpen()) {
        open();
        return ;
    }
    QDateTime timestamp = QDateTime::currentDateTime();

    _stream << timestamp.toString("yyyy.MM.dd hh:mm:ss.zzz") << SEPARATOR
    << levelToString(level) << SEPARATOR
    << (NULL != source ? source->category : "") << SEPARATOR
    << (NULL != source ? source->source : "") << SEPARATOR
    << (NULL != source ? source->method : "") << SEPARATOR
    << (NULL != source ? source->type : "") << SEPARATOR
    << message << "\n";

}


TLogger::TLogger(const bool isEnabled, const QString &newTag, const QString &fileName)
{
    _init = false;
    _tag = newTag ;
    _enabled = isEnabled ;
    _fileName = fileName ;
    _isWriteImmediate = false;
}

TLogger::~TLogger()
{
    close();
}

bool TLogger::isEnabled()
{
    return _enabled ;
}

void TLogger::enable(const bool how)
{
    _enabled = how;
    if (!_enabled) {
        close();
    }
}

TLogger::ELogLevel TLogger::getLevel()
{
    return _level ;
}

void TLogger::setLevel(const ELogLevel newLevel)
{
    _level = newLevel ;
}

QString TLogger::getFile()
{
    return _fileName ;
}

void TLogger::setFile(const QString& newFile)
{
    close();
    _fileName = newFile ;
    if (isEnabled()) {
        open();
    } else {
        close();
    }
}

void TLogger::close()
{
    if (_file.isOpen()) {
        _file.close();
    }
}


void TLogger::start()
{
    KSharedConfigPtr    config = KSharedConfig::openConfig(CONFIG_COMPONENT);
    KConfigGroup        logGroup(config, CONFIG_GROUP_LOG);
    _enabled    = logGroup.readEntry(CONFIG_LOG_KEY_ENABLED, true);
    if (_fileName.isEmpty()) {
        _fileName   = logGroup.readEntry(CONFIG_LOG_KEY_FILENAME, "");
    }
    _level = (ELogLevel)logGroup.readEntry(CONFIG_LOG_KEY_LEVEL, int(TLogger::DEBUG));
    _isWriteImmediate = logGroup.readEntry(CONFIG_WRITE_IMMEDIATE, false);
    //ONLY TO WRITE THE ENTRY logGroup.writeEntry(CONFIG_WRITE_IMMEDIATE, true );
    if (_fileName.isEmpty()) {
        /* this code from Lancelot by Ivan Cukic */
        QDir dir;
        QString path = KStandardDirs::locateLocal("data", KLABELER_STDDIR, true);
        if (!path.endsWith('/')) {
            path += '/';
        }
        path += "log/";

        if (!dir.exists(path)) {
            if (!dir.mkpath(path)) {
                notifyError();
                return ;
            }
        }

        QDate date = QDate::currentDate();
        path += "log-" + _tag + QString::number(date.year())
                + '-' + QString::number(date.month());

        _fileName = path;
    }
    _init = true;
    open();
}


void TLogger::open()
{
    if (!isEnabled() || _file.isOpen()) {
        return ;
    }
    _file.setFileName(_fileName);
    if (_file.open(QFile::WriteOnly | QFile::Append)) {
        _stream.setDevice(&_file);
        if (_isWriteImmediate) {
            _stream.flush();
        }
    } else {
        notifyError();
        // Show error message
    }
}


void TLogger::notifyError()
{
    KNotification * notify = new KNotification("ErrorOpeningLog");
    notify->setText(i18n("Failed to open the log file. Logging is disabled."));
    notify->setPixmap(KIcon("view-history").pixmap(KIconLoader::SizeMedium, KIconLoader::SizeMedium));
    notify->sendEvent();
    // Show error message
}

QString TLogger::levelToString(const ELogLevel level)
{
    switch (level) {
    case TRACE: return "TRACE";
    case DEBUG: return "DEBUG";
    case INFO: return "INFO";
    case WARNING: return "WARNING";
    case ERROR: return "ERROR";
    case FATAL: return "FATAL";
    default: return "?";
    }
}

void TLogger::trace(const QString &message)
{
    log(TLogger::TRACE, NULL, message);
}

void TLogger::debug(const QString &message)
{
    log(TLogger::DEBUG, NULL, message);
}

void TLogger::info(const QString &message)
{
    log(TLogger::INFO, NULL, message);
}

void TLogger::warning(const QString &message)
{
    log(TLogger::WARNING, NULL, message);
}

void TLogger::error(const QString &message)
{
    log(TLogger::ERROR, NULL, message);
}

void TLogger::fatal(const QString &message)
{
    log(TLogger::FATAL, NULL, message);
}

//--------------------------------------------

void TLogger::trace(const LogParam *source, const QString &message)
{
    log(TLogger::TRACE, source, message);
}

void TLogger::debug(const LogParam *source, const QString &message)
{
    log(TLogger::DEBUG, source, message);
}

void TLogger::info(const LogParam *source, const QString &message)
{
    log(TLogger::INFO, source, message);
}

void TLogger::warning(const LogParam *source, const QString &message)
{
    log(TLogger::WARNING, source, message);
}

void TLogger::error(const LogParam *source, const QString &message)
{
    log(TLogger::ERROR, source, message);
}

void TLogger::fatal(const LogParam *source, const QString &message)
{
    log(TLogger::FATAL, source, message);
}
